package com.enfi.api.modules.ext.controller;

import com.enfi.api.modules.ext.service.GroupService;
import com.enfi.api.modules.ext.websocket.domain.GroupSession;
import com.enfi.api.modules.ext.websocket.domain.Message;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;

import java.security.Principal;
import java.util.Set;

/**
 * @author xukk
 * @date 2020/3/11
 */
@Controller
public class DefaultController {

    @Autowired
    private SimpMessagingTemplate messagingTemplate;
    @Autowired
    private GroupService groupService;

    @MessageMapping("/publicMessage")
    @SendTo("/topic/public")
    public Message sendPublicMessage(@Payload Message chatMessage) {
        return chatMessage;
    }


    @MessageMapping("/privateMessage")
    public void sendPrivateMessage(@Payload Message msg, Principal principal) {
        msg.setFrom(principal.getName());
        //将消息推送到指定路径上
        messagingTemplate.convertAndSendToUser(msg.getTo(), "/topic/chat", msg);
    }

    @MessageMapping("/message")
    public void sendTopicMessage(@Payload Message msg, Principal principal) {
        msg.setFrom(principal.getName());
        //将消息推送到指定路径上
        messagingTemplate.convertAndSendToUser(msg.getTo(), "/message/"+msg.getTopic(), msg);
    }

    @MessageMapping("/groupMessage")
    public void sendGroupMessage(@Payload Message msg, Principal principal) {
        msg.setFrom(principal.getName());
        Set<String> a = GroupSession.getGroup().keySet();
        String pushWay="web";
        if (!CollectionUtils.isEmpty(a)) {
            a.forEach(v->{
                if(groupService.checkGroupPush(pushWay,v, Lists.newArrayList(msg.getTo()), Lists.newArrayList())){
                    Set<String> b = GroupSession.getGroup().get(v);
                    if (!CollectionUtils.isEmpty(b)) {
                        b.forEach(k -> {
                            messagingTemplate.convertAndSendToUser(k, "/topic/group", msg);
                        });
                    }
                }
            });
        }
    }
}
